import csv
import os
import shutil
import sys

dirname = os.path.dirname(__file__)
lib_dir = os.path.join(dirname, "lib_files")
hdc_cmd_path = 'hdc'
# 需要拉下的文件，以及存放目标路径
csv_path = os.path.join(dirname, "res_use.csv")
# 作报告用，统计缺失文件
origin_csv_path = os.path.join(dirname, "res_use.csv")


class FileTarget:
    def __init__(self):
        self.target_path = None
        self.file_name = None
        self.system_path = None


def read(path=csv_path):
    with open(path, 'rt', newline='', encoding='utf-8') as csvfile:
        spamreader = csv.DictReader(csvfile)
        resources = []
        for row in spamreader:
            action_v3: FileTarget = FileTarget()
            action_v3.file_name = row['file_name']
            action_v3.target_path = row["target_path"]
            resources.append(action_v3)
        # 已经找的文件，将路径缓存，后面遇到相同文件直接赋值
        local_cache_set = {}
        for res in resources:
            if res.file_name not in cacheSet:
                if res.file_name not in local_cache_set:
                    cmd = f"{hdc_cmd_path} shell find / -name '{res.file_name}'"
                    print(cmd)
                    handle_result = os.popen(cmd)
                    handle_result_str = handle_result.readlines()
                    print(f'find cmd result {handle_result_str}')
                    last_line = handle_result_str[-1].strip()
                    # last_line = '/system/lib64/libadbd_fs.so'
                    res.system_path = last_line
                    local_cache_set[res.file_name] = last_line
                    print(last_line)
                else:
                    res.system_path = local_cache_set[res.file_name]
                print(
                    f"{res.file_name}, {res.target_path} {res.system_path}")
            else:
                print("havae")

        return resources

def report(path=origin_csv_path):
    with open(path, 'rt', newline='', encoding='utf-8') as csvfile:
        spamreader = csv.DictReader(csvfile)
        resources = []
        for row in spamreader:
            action_v3: FileTarget = FileTarget()
            action_v3.file_name = row['file_name']
            action_v3.target_path = row["target_path"]
            resources.append(action_v3)
        # 已经找的文件，将路径缓存，后面遇到相同文件直接赋值
    for resource in resources:
        target_file = os.path.join(os.path.join(dirname, resource.target_path), resource.file_name)
        if not os.path.exists(target_file):
            print(f"miss {resource.file_name} {target_file}")


def pullCopy():
    global cacheSet
    if not os.path.exists(lib_dir):
        os.makedirs(lib_dir)
    # 缓存本地已经拉取下来的文件
    cacheSet = set()
    lib_files = os.listdir(lib_dir)
    for lib_file in lib_files:
        cacheSet.add(lib_file)
    resources = read(path=csv_path)
    for resource in resources:
        check_file = os.path.join(lib_dir, resource.file_name)
        # 已经拉取下来的文件中没有该文件，则向设备拉取文件
        if not os.path.exists(check_file):
            pull_result = os.popen(
                f"{hdc_cmd_path} file recv {resource.system_path} {check_file}")
            pull_result_str = pull_result.read()
            print(pull_result_str)
            print(f"pull finish {resource.file_name}")
        # 将文件复制到指定的多层文件夹中
        target_path_dir = os.path.join(dirname, resource.target_path)
        if not os.path.exists(target_path_dir):
            os.makedirs(target_path_dir)
        shutil.copy(check_file, target_path_dir)
        if os.path.exists(os.path.join(target_path_dir, resource.file_name)):
            print(f"copy finish {resource.file_name}")
        else:
            print(f"copy failed {resource.file_name}")


if __name__ == '__main__':
    print(sys.platform)
    pullCopy()
    print(">>>>>>>>>>>>>>>>>> report >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
    report()



